package guard

import (
	"github.com/gin-gonic/gin"
	"strconv"
)

type PluginsParam struct {
	Page       int
	PageSize   int
	Filter     int
	Free       int
	Order      string
	Lang       string
	CategoryID int
}

type PluginsParamGuard struct{}

func Plugins() *PluginsParamGuard {
	return new(PluginsParamGuard)
}

func (a *PluginsParamGuard) Guard(ctx *gin.Context) (interface{}, error) {

	var l PluginsParam

	l.Page, _ = strconv.Atoi(ctx.Query("page"))
	if l.Page == 0 {
		l.Page = 1
	}
	l.Free, _ = strconv.Atoi(ctx.Query("free"))
	if l.Free == 0 {
		l.Free = 1
	}
	l.PageSize, _ = strconv.Atoi(ctx.Query("page_size"))
	if l.PageSize == 0 {
		l.PageSize = 20
	}
	l.Filter, _ = strconv.Atoi(ctx.Query("filter"))
	l.Order = ctx.Query("order")
	// TODO: 限制排序字段
	// 最新/最多人点赞
	if l.Order == "" {
		l.Order = "order"
	}
	l.Lang = ctx.Query("lang")
	if l.Lang == "" {
		l.Lang = "cn"
	}
	if l.Filter == 3 {
		l.CategoryID, _ = strconv.Atoi(ctx.Query("category_id"))
	}

	return l, nil
}

func GetPluginsParam(c *gin.Context) PluginsParam {
	return c.MustGet("param").(PluginsParam)
}

type PluginsBuyParam struct {
	Page     int
	PageSize int
	Lang     string
}

type PluginsBuyParamGuard struct{}

func PluginsBuy() *PluginsBuyParamGuard {
	return new(PluginsBuyParamGuard)
}

func (a *PluginsBuyParamGuard) Guard(ctx *gin.Context) (interface{}, error) {

	var l PluginsBuyParam

	l.Page, _ = strconv.Atoi(ctx.Query("page"))
	if l.Page == 0 {
		l.Page = 1
	}
	l.PageSize, _ = strconv.Atoi(ctx.Query("page_size"))
	if l.PageSize == 0 {
		l.PageSize = 20
	}
	l.Lang = ctx.Query("lang")
	if l.Lang == "" {
		l.Lang = "cn"
	}

	return l, nil
}

func GetPluginsBuyParam(c *gin.Context) PluginsBuyParam {
	return c.MustGet("param").(PluginsBuyParam)
}

type PluginsDownloadParam struct {
	Uuid string
}

type PluginsDownloadParamGuard struct{}

func PluginsDownload() *PluginsDownloadParamGuard {
	return new(PluginsDownloadParamGuard)
}

func (a *PluginsDownloadParamGuard) Guard(ctx *gin.Context) (interface{}, error) {

	var l PluginsDownloadParam

	err := ctx.BindJSON(&l)

	if err != nil {
		return nil, err
	}

	return l, nil
}

func GetPluginsDownloadParam(c *gin.Context) PluginsDownloadParam {
	return c.MustGet("param").(PluginsDownloadParam)
}
